<template>
	<el-card style="max-width: 480px;margin: 0 auto;margin-top: 300px;">
		<template #header>
			<div class="card-header" style="text-align: center;">
				<span>登录</span>
			</div>
		</template>
		<div class="login-container">
			<el-form v-model="loginForm" ref="loginFormRef" :rules="rules" label-width="80px" class="login-form">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm">登录</el-button>
				</el-form-item>
			</el-form>
		</div>
	</el-card>
</template>

<script setup>
	import {
		reactive,
		inject
	} from 'vue';
	import {
		ElForm,
		ElFormItem,
		ElInput,
		ElButton,
		ElCard
	} from 'element-plus';
	import router from '../../src/router/index.js'; // 导入路由对象
	let axios = inject("axios");
	const myElMessage = inject("elMessage");
	const loginForm = reactive({
		username: '',
		password: ''
	});

	function submitForm() {
		// 表单验证通过，执行登录逻辑
		let username = loginForm.username;
		let password = loginForm.password;
		let url = "/api/admin/login"
		axios.post(url, loginForm).then((r) => {
			if (r.data.ok) {

				let user = r.data.data.user;

				localStorage.setItem("userinfo", JSON.stringify(user));
				router.push("/index");
			} else {
				myElMessage("登录失败", "error")
			}
		});
	}
</script>

<style>
	.login-container {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.login-form {
		width: 300px;
	}
</style>